package ar.edu.unrn.lia.bean.datamodel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import ar.edu.unrn.lia.model.Cuenta;
import ar.edu.unrn.lia.service.CuentaService;

public class LazyCuentaDataModel extends LazyDataModel<Cuenta> {

	private static final long serialVersionUID = 1L;

	private static final String ORDER_DEFAULT = "id";

	private List<Cuenta> list;

	@Inject
	CuentaService entityService;

	public CuentaService getEntityService() {
		return entityService;
	}

	public LazyCuentaDataModel() {
		super();
	}

	public LazyCuentaDataModel(CuentaService entityService) {
		super();
		this.entityService = entityService;
	}

	@Override
	public List<Cuenta> load(int startingAt, int maxPerPage, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		try {		

				list = getEntityService()
						.getList(
								startingAt,
								maxPerPage,
								filters,
								(sortField == null ? ORDER_DEFAULT : sortField),
								(sortOrder.name().equals(SortOrder.ASCENDING
										.toString())));

		} catch (Exception e) {
			e.printStackTrace();
			list = new ArrayList<Cuenta>(0);
		}

		// set the total of list
		if (getRowCount() <= 0) {
			setRowCount(getEntityService().getCount(filters).intValue());
		}

		// set the page dize
		setPageSize(maxPerPage);

		return list;
	}

	@Override
	public Object getRowKey(Cuenta entity) {
		return entity.getId();
	}

	@Override
	public Cuenta getRowData(String entityId) {
		Integer id = Integer.valueOf(entityId);

		for (Cuenta entity : list) {
			if (id.equals(entity.getId())) {
				return entity;
			}
		}

		return null;
	}

}